# -*- coding: utf-8 -*-
import docx
from docx.shared import Inches, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
import os
import openpyxl
from docx import Document
from win32com.client import constants, gencache  # 用于将Word转换为PDF


def writeLetter(name):
    """
    生成邀请函Word文档，保存至'邀请函'文件夹下
    :param name: 姓名（从Excel读取）
    """
    doc = docx.Document()  # 创建新的Word文档

    # 设置默认字体为微软雅黑
    doc.styles['Normal'].font.name = u'微软雅黑'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')

    # 添加标题，居中对齐
    paragraph1 = doc.add_heading('校庆邀请函', level=1)
    paragraph1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

    # 添加称呼段
    doc.add_paragraph(f'尊敬的{name}同学:')

    # 添加正文内容段落
    paragraph2 = doc.add_paragraph()
    paragraph2.add_run(
        '        2024年4月26日，学院将迎来65周年华诞。'
        '学院热切期盼广大校友拨冗光临，回到这个无数次出现在梦里的老地方，'
        '共忆风华正茂，共襄校庆盛典，共谋发展大计！'
    )
    
    # 空行
    doc.add_paragraph() 

    # 添加右对齐落款
    paragraph3 = doc.add_paragraph()
    paragraph3.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    paragraph3.add_run("学生会")

    # 添加日期（右对齐）
    paragraph4 = doc.add_paragraph()
    paragraph4.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    paragraph4.add_run("2024年4月26日")

    # 创建目录
    dir_path = '邀请函'
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

    # 保存 Word 文件
    file_path = os.path.join(dir_path, f"{name}邀请函.docx")
    doc.save(file_path)


def createPdf(wordPath, pdfPath):
    """
    使用win32com将Word文档转换为PDF
    :param wordPath: Word文件路径
    :param pdfPath: 输出PDF文件路径
    """
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(wordPath, ReadOnly=1)
    doc.ExportAsFixedFormat(
        pdfPath,
        constants.wdExportFormatPDF,
        Item=constants.wdExportDocumentWithMarkup,
        CreateBookmarks=constants.wdExportCreateHeadingBookmarks
    )
    word.Quit(constants.wdDoNotSaveChanges)


# 加载Excel文件
wb = openpyxl.load_workbook("计应B班校友名录.xlsx")
ws = wb.worksheets[0]

# 遍历C2至C46的每一个名字
for row in ws['C2:C46']:
    for cell in row:
        name = str(cell.value).strip()  # 强制转换为字符串并去除空格
        if not name:
            continue

        print(f"正在生成{name}的邀请函")
        
        # Step 1: 生成 Word 邀请函
        writeLetter(name)

        # Step 2: 添加图片并覆盖保存
        doc_path = f'邀请函/{name}邀请函.docx'
        doc = Document(doc_path)
        try:
            doc.add_picture('result.png', width=Cm(3))  # 添加图片
        except Exception as e:
            print(f"{name} 添加图片失败: {e}")
        doc.save(doc_path)

        # Step 3: 转换为PDF
        pdf_output_path = f'C:\\Users\\admin\\Desktop\\邀请函PDF\\{name}邀请函.pdf'
        os.makedirs(os.path.dirname(pdf_output_path), exist_ok=True)
        try:
            createPdf(os.path.abspath(doc_path), pdf_output_path)
        except Exception as e:
            print(f"{name} PDF生成失败: {e}")
